<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-login login-con">
    <view class="welcome">
      欢迎登录
    </view>
    <view class="shop-name">
      {{ configuration.bsTitleContent }}
    </view>
    <view class="form">
      <uni-forms ref="loginFormRef">
        <uni-forms-item name="userName">
          <uni-easyinput
            v-model="dataForm.userName"
            class="form-item"
            :class="errorTips === 1 ? 'error-border' : ''"
            type="text"
            placeholder="用户名/手机号"
            place
            @focus="handleInpFocus(1)"
          />
          <view
            v-if="errorTips === 1"
            class="error-text"
          >
            请输入用户名/手机号
          </view>
        </uni-forms-item>
        <uni-forms-item name="password">
          <uni-easyinput
            v-model="dataForm.password"
            class="form-item"
            :class="errorTips === 2 ? 'error-border' : ''"
            type="password"
            placeholder="密码"
            @focus="handleInpFocus(2)"
            @confirm="submit()"
            @blur="dataForm.password = dataForm.password.replace(/\s/g, '')"
          />
          <view
            v-if="errorTips === 2"
            class="error-text"
          >
            请输入密码
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>
    <button
      class="login-btn"
      type="default"
      hover-class="none"
      @tap="submit()"
    >
      登录
    </button>
    <view
      class="find-pwd"
      @tap="findPwd()"
    >
      忘记密码？
    </view>
    <view class="footer">
      <view class="copy-right">
        注册商家账号请前往PC端注册
      </view>
      <view class="copy-right">
        {{ merchantPlatformUrl }}
      </view>
    </view>

    <verify
      ref="verifyRef"
      :mode="'pop'"
      captcha-type="blockPuzzle"
      :v-space="15"
      :img-size="{ width: '320px', height: '160px' }"
      @success="login"
    />
  </view>
</template>

<script setup>
import { encrypt } from '@/utils/crypto'

const { shopMenuList, clearLoginInfo } = util
const userStore = useUserStore()
// 商家端PC域名
const merchantPlatformUrl = import.meta.env.VITE_APP_MERCHANT_PKATFORM_URL
const dataForm = reactive({
  userName: '',
  password: '',
  uuid: '',
  captcha: ''
})
const errorTips = ref(0)
// 网站配置信息
const configuration = ref({})
onShow(() => {
  // 请求后台配置信息
  getWebConfig()
})

/**
 * 获取后台商家端配置信息
 */
const getWebConfig = () => {
  const params = {
    url: '/sys/webConfig/getActivity',
    method: 'GET'
  }
  http.request(params).then(({ data: res }) => {
    res.bsTitleContentCn = res.bsTitleContentCn || '蓝海-商家端'
    res.bsTitleContentEn = res.bsTitleContentEn || 'LANHAI-Shop'
    configuration.value = res
  })
}
const verifyRef = ref(null)
/**
 * 触发提交表单
 */
const submit = () => {
  if (dataForm.userName.trim() === '') {
    errorTips.value = 1
  } else if (dataForm.password.trim() === '') {
    errorTips.value = 2
  } else {
    errorTips.value = 0
    verifyRef.value?.show()
  }
}

/**
 * 输入框聚焦
 */
const handleInpFocus = (i) => {
  if (errorTips.value === i) {
    errorTips.value = 0
  }
}

/**
 * 找回密码
 */
const findPwd = () => {
  uni.navigateTo({
    url: '/package-settings/pages/find-pwd/find-pwd'
  })
}

const loginFormRef = ref(null)
/**
 * 登录
 */
const login = (verifyResult) => {
  loginFormRef.value?.validate().then(() => {
    // uni.showLoading()
    const params = {
      url: '/shopLogin',
      method: 'POST',
      data: {
        captchaVerification: verifyResult.captchaVerification,
        passWord: encrypt(dataForm.password),
        userName: dataForm.userName
      }
    }
    http.request(params).then(async (data) => {
      uni.hideLoading()
      if (data.code !== '00000') {
        uni.showToast({
          title: data.msg,
          icon: 'none',
          duration: 1500
        })
        return
      }
      const { data: res } = data
      uni.setStorageSync('bbcToken_us', res.accessToken)
      uni.setStorageSync('bbcLoginResult', res) // 保存整个登录数据
      await shopMenuList()
      let user
      try {
        user = await userStore.login()
        // user = await $store.dispatch('user/login')
        // 重置菜单路由
        // router.options.isAddDynamicMenuRoutes = false
      } catch (error) {
        return
      }
      if (user.shopStatus === 4 || user.shopStatus === 5 || user.isPassShop === 0) {
        // 未开店，跳转申请开店
        // await $router.replace({name: 'shopProcess'})
        clearLoginInfo()
        uni.showModal({
          title: '提示',
          content: '请在PC端先完成开店申请',
          showCancel: false,
          success (res) {
            if (res.confirm) {
              clearLoginInfo()
            }
          }
        })
      } else {
        const payTypeParams = {
          url: '/sys/config/paySettlementType',
          method: 'get'
        }
        http.request(payTypeParams).then(({ data }) => {
          if (data) {
            const paySettlementType = JSON.parse(data).paySettlementType
            uni.setStorageSync('bbcPaySettlementType', paySettlementType)
          }
          // 已开店，跳转首页
          uni.switchTab({
            url: '../index/index'
          })
        })
      }
    })
  })
}

</script>

<style lang="scss" scoped>
@use './login.scss';
</style>
